package dingtalk

import (
	"fmt"
	dingtalkrobot "github.com/JetBlink/dingtalk-notify-go-sdk"
	"github.com/spf13/viper"
	"os"
	"strconv"
)

var (
	Config      *viper.Viper
	DINGTALKURL string
	WEBHOOK     string
	SECRET      string
	ENV         string
)

func init() {
	//读取配置文件
	path, err := os.Getwd()
	if err != nil {
		panic(err)
	}

	Config = viper.New()
	Config.AddConfigPath(path)     //设置读取的文件路径
	Config.SetConfigName("config") //设置读取的文件名
	Config.SetConfigType("yaml")   //设置文件的类型
	//尝试进行配置读取
	if err := Config.ReadInConfig(); err != nil {
		panic(err)
	}
	// 读取配置并存入全局变量
	DINGTALKURL = Config.GetString("dingtalk.url")
	WEBHOOK = Config.GetString("dingtalk.webhook")
	SECRET = Config.GetString("dingtalk.secret")
	ENV = Config.GetString("dingtalk.title")
}

func Send(totalCount int, okCount int, errCount int, okRateStr string, errMsg string) {
	//消息示例
	//巡检通知v2
	//环境：中枢系统
	//接口总数：34
	//失败数/成功数：1 / 33
	//成功率：97%
	//错误信息：
	//code:200  success:false  url:http://172.18.110.124:8080/api/v2/operation/apply/zs/instance/application/list
	robot := dingtalkrobot.NewRobot(WEBHOOK, SECRET)
	content := "【API巡检通知】\n" +
		"环境：" + ENV + "\n" +
		"接口总数：" + strconv.Itoa(totalCount) + "\n" +
		"成功数/失败数：" + strconv.Itoa(okCount) + " / " + strconv.Itoa(errCount) + "\n" +
		"成功率：" + okRateStr + "\n" +
		errMsg
	err := robot.SendTextMessage(content, []string{""}, true)
	if err != nil {
		fmt.Println(err)
		return
	}

}
